package com.yangxc.applet.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.bodyanalysis.AipBodyAnalysis;
import com.baidu.aip.imageprocess.AipImageProcess;
import com.baidu.aip.ocr.AipOcr;
import com.yangxc.applet.api.dto.BodySeg;
import com.yangxc.applet.service.ServerService;
import com.yangxc.applet.utils.PngColoringUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.awt.*;
import java.util.HashMap;

/**
 * @author yangxc
 * @version 1.0.0
 * @ClassName ServerServiceImpl.java
 * @Description TODO
 * @createTime 2022年10月02日 17:39:00
 */
@Slf4j
@Service
public class ServerServiceImpl implements ServerService {
    
    @Resource
    AipBodyAnalysis aipBodyAnalysis;
    @Resource
    AipOcr aipOcr;
    @Resource
    AipImageProcess aipImageProcess;
    
    @Override
    public String today() {
        String s = HttpUtil.get("https://www.ipip5.com/today/api.php");
        log.info("请求历史上今天接口返回：{}", s);
        return s;
    }
    
    @Override
    public String imgChange(MultipartFile file,String color) {
        log.info("照片换底方法，换成：{}", color);
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("type", "foreground");
        // 可选：设置网络连接参数
        aipBodyAnalysis.setConnectionTimeoutInMillis(2000);
        aipBodyAnalysis.setSocketTimeoutInMillis(60000);
    
        // 调用接口
        JSONObject res = new JSONObject();
        try {
            res = aipBodyAnalysis.bodySeg(file.getBytes(), options);
            log.info("百度人像分割返回：{}",res);
        }catch (Exception e) {
            throw new RuntimeException("调用百度人像分割接口异常");
        }
        BodySeg bodySeg = JSON.parseObject(res.toString(), BodySeg.class);
        if (bodySeg.getPerson_num() < 1) {
            throw new RuntimeException("处理失败，未检测到人脸");
        }
    
        //背景色替换
        return PngColoringUtil
                .changePNGBackgroudColorByBase64(Base64.decode(bodySeg.getForeground()), getBackGroundColor(color));
    }
    
    @Override
    public String cleanBg(MultipartFile file) {
        log.info("照片去背景方法");
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("type", "foreground");
        // 可选：设置网络连接参数
        aipBodyAnalysis.setConnectionTimeoutInMillis(2000);
        aipBodyAnalysis.setSocketTimeoutInMillis(60000);
    
        // 调用接口
        JSONObject res = new JSONObject();
        try {
            res = aipBodyAnalysis.bodySeg(file.getBytes(), options);
            log.info("百度人像分割返回：{}",res);
        }catch (Exception e) {
            throw new RuntimeException("调用百度人像分割接口异常");
        }
        BodySeg bodySeg = JSON.parseObject(res.toString(), BodySeg.class);
        return bodySeg.getForeground();
    }
    
    @Override
    public String imageOcr(MultipartFile file) {
        // 可选：设置网络连接参数
        aipOcr.setConnectionTimeoutInMillis(2000);
        aipOcr.setSocketTimeoutInMillis(60000);
    
        // 调用接口
        //String path = "C:\\Users\\yangxc\\Desktop\\ocr.png";
        JSONObject res = new JSONObject();//new JSONObject("{\"words_result\":[{\"words\":\"1.10月份资原回仪非期大家确以\"},{\"words\":\"1.1 Jenkins maven git相关\"},{\"words\":\"1.211.上云小康确认\"},{\"words\":\"统一支付\"},{\"words\":\"电商\"},{\"words\":\"1.311月份elk大家确认\"},{\"words\":\"云下搭建后接入\"},{\"words\":\"1.611月份代码质量维护大家确认\"},{\"words\":\"1.4监控大家确认\"},{\"words\":\"skywalking云下搭建后接入\"},{\"words\":\"1.5 gitlab+流水线接入\"},{\"words\":\"1.7 meterphere大家学习\"},{\"words\":\"手册\"},{\"words\":\"1.8分享部分人\"},{\"words\":\"决策方式及分享方式\"}],\"log_id\":1579683552459701303,\"words_result_num\":15}");
        try {
            res = aipOcr.basicGeneral(file.getBytes(), new HashMap<String, String>());
            log.info("通用文字识别接口返回：{}", res);
        }catch (Exception e) {
            throw new RuntimeException("调用百度人像分割接口异常");
        }
        //获取JSON对象里提取图片文字信息数组
        JSONArray jsonArray = res.getJSONArray("words_result");
        //循环打印信息
        StringBuilder sb = new StringBuilder();
        for(int i = 0;i<jsonArray.length();i++){
            sb.append("\n").append(jsonArray.getJSONObject(i).get("words"));
        }
        return sb.toString();
    }
    
    @Override
    public String selfieAnime(MultipartFile file) {
        HashMap<String, String> options = new HashMap<String, String>();
    
        options.put("type", "anime");
        options.put("mask_id", "3");
    
        JSONObject res = new JSONObject();
        try {
            res = aipImageProcess.selfieAnime(file.getBytes(), options);
            log.info("通用人物动漫化接口返回：{}", res);
        }catch (Exception e) {
            throw new RuntimeException("调用人物动漫化接口异常");
        }
        return res.getString("image");
    }
    
    
    /*@Override
    public String imgChange(MultipartFile file,String color) {
        log.info("照片换底方法，换成：{}", color);
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("type", "foreground");
        // 可选：设置网络连接参数
        aipBodyAnalysis.setConnectionTimeoutInMillis(2000);
        aipBodyAnalysis.setSocketTimeoutInMillis(60000);
        
        // 调用接口
        JSONObject res = new JSONObject();
        try {
            res = aipBodyAnalysis.bodySeg(file.getBytes(), options);
            log.info("百度人像分割返回：{}",res);
        }catch (Exception e) {
            throw new RuntimeException("调用百度人像分割接口异常");
        }
        BodySeg bodySeg = JSON.parseObject(res.toString(), BodySeg.class);
        if (bodySeg.getPerson_num() < 1) {
            throw new RuntimeException("处理失败，未检测到人脸");
        }
    
        
        String path = "C:\\Users\\yangxc\\Downloads\\bg.jpg";
        byte[] bytes = null;
        try {
            bytes = Util.readFileByBytes(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //背景色替换
        return PngColoringUtil
                .changeBgImageByBase64(Base64.decode(bodySeg.getForeground()), bytes);
    }*/
    
    private Color getBackGroundColor(String colorStr) {
        Color backgroudColor = null;
        if(colorStr.equals("red")){
            backgroudColor = Color.RED;
        }
        if(colorStr.equals("blue")){
            backgroudColor = Color.BLUE;
        }
        if(colorStr.equals("black")){
            backgroudColor = Color.BLACK;
        }
        if(colorStr.equals("white")){
            backgroudColor = Color.WHITE;
        }
        return backgroudColor;
    }
}
